<?php

/**
 * Pes for PHP 5.3+
 *
 * Copyright (c) 2013 phpeskill.com (http://www.pescms.com)
 *
 * For the full copyright and license information, please view
 * the file LICENSE.md that was distributed with this source code.
 */

namespace App;

use Model\Home\OptionModel as OptionModel;
use Expand\Home\Label as Label;
use Core\Cache\FileCache as FileCache;

/**
 * 门面类
 * 用于系统的前台和用户中心
 * @author LazyPHP
 * @version 1.0
 */
class Facade extends All {

    private $siteSetting, $theme;
    public $Categorys;

    /**
     * 前台构造函数
     * 本函数包含以下动作:
     * 网站主题，基础信息，状态检查
     */
    public function __construct() {
        $this->theme = OptionModel::getOption('7');
        $this->checkTheme();
        $getResult = OptionModel::getSiteSetting();
        foreach ($getResult as $key => $value) {
            if ($value['option_name'] == 'siteurl') {
                $this->siteSetting[$value['option_name']] = $value['value'];
                $this->siteSetting['css'] = "{$value['value']}/Theme/Home/{$this->theme['value']}/css";
                $this->siteSetting['js'] = "{$value['value']}/Theme/Home/{$this->theme['value']}/js";
                $this->siteSetting['img'] = "{$value['value']}/Theme/Home/{$this->theme['value']}/img";
            } else {
                $this->siteSetting[$value['option_name']] = $value['value'];
            }
        }
        $this->systemParam();
        $this->assign('site', $this->siteSetting);
        $this->assign('catid', $this->findCatid());
        $this->assign('cat', $this->finCatInfo($this->findCatid()));
        $this->Categorys = $this->getCategory();
        $this->assign('Categorys', $this->Categorys);
        $this->checkSiteStatus();
        $this->cookieLogin();
        $this->loadAd();
    }

    /**
     * 检查网站状态
     */
    private function checkSiteStatus() {
        if ($this->siteSetting['sitestatus'] == '0') {
            exit($this->siteSetting['closeReason']);
        }
    }

    /**
     * 检查主题是否存在
     */
    private function checkTheme() {
        if (!is_dir("./Theme/Home/{$this->theme['value']}")) {
            exit("程序主题{$this->theme['value']}不存在!");
        }
    }

    /**
     * 查找当前的分类ID
     */
    private function findCatid() {
        $id = (int) $_GET['id'];
        if (MODULE == 'Page') {
            return $id;
        } else {
            switch (ACTION) {
                case 'list':
                    return $id;
                    break;
                case 'view':
                    $db = $this->db(strtolower(MODULE));
                    $findResult = $db->field('catid')->where('id =:id')->find(array('id' => $id));
                    return $findResult['catid'];
                    break;
            }
        }
    }

    /**
     * 获取分类的信息
     * @param type $id 分类ID
     */
    private function finCatInfo($id) {
        $db = $this->db('category');
        $result = $db->where('id =:id')->find(array('id' => $id));
        return $result;
    }

    /**
     * 列出所有分类
     * @return type 返回分类数组
     */
    private function getCategory() {
        $db = $this->db('category');
        $result = $db->select();
        foreach ($result as $key => $value) {
            $tempArray[$value['id']] = $value;
        }
        return $tempArray;
    }

    /**
     * 检查cookie，获取登陆状态
     */
    private function cookieLogin() {
        if (!empty($_COOKIE['recordLogin']) && empty($_SESSION['user'])) {
            $db = $this->db('cookie');
            $data['cookie'] = $_COOKIE['recordLogin'];
            $data['createtime'] = time() - 864000;
            $findCookie = $db->where('cookie = :cookie and createtime >= :createtime')->find($data);
            if (!empty($findCookie)) {
                //获取用户信息
                $db->tableName('user');
                $userInfo = $db->where("uid = {$findCookie['uid']}")->find();
                if (empty($userInfo)) {
                    setcookie("recordLogin", "", time() - 3600);
                    $this->error('用户不存在!', $this->url('User-Login-index'));
                }
                $_SESSION['user'] = $userInfo;
            }
        }
    }

    /**
     * 加载广告
     */
    private function loadAd() {
        $adCache = new FileCache();
        $ad = $adCache->loadCache("ad");
        if (empty($ad)) {
            $db = $this->db('ad');
            $result = $db->where('status = 1')->select();
            foreach ($result as $key => $value) {
                $list[$value['name']] = $value;
            }
            $ad = $adCache->createCache('ad', $list);
        }
        $this->assign('ad', $ad);
    }

    /**
     * 加载系统变量
     */
    private function systemParam() {
        $systemCache = new FileCache();
        $system = $systemCache->loadCache("system");
        if (empty($system)) {
            $systemParam = OptionModel::getOption('12');
            $system = $systemCache->createCache('system', json_decode($systemParam['value']));
        }
        $this->assign('system', $system);
    }

    /**
     * 判断是否已经登陆
     */
    protected function isLogin() {
        if (empty($_SESSION['user'])) {
            switch (MODULE) {
                case 'Register':
                case 'Login':
                    break;
                default :
                    $this->error('您还没有登陆!', $this->url('User-Login-index'));
            }
        } else {
            switch (MODULE) {
                case 'Register':
                case 'Login':
                    if (ACTION != 'logout') {
                        header("Location: {$this->url('User-Index-index')}");
                    }
            }
        }
    }

    /**
     * 加载页眉
     */
    public final function header($theme = 'header') {
        $this->display($theme);
    }

    /**
     * 加载页脚
     */
    public final function footer($theme = 'footer') {
        $this->display($theme);
    }

    /**
     * 加载侧栏
     */
    public final function sidebar($theme = 'sidebar') {
        $this->display($theme);
    }

    /**
     * 加载对应的主题模块
     * @param type $theme
     */
    public final function display($theme = '') {
        $funcfile = ITEM . "\\Func\\Func";
        $func = new $funcfile();
        $label = 'Expand\Label';
        if (!empty($this->tVar)) {
            extract($this->tVar, EXTR_OVERWRITE);
        }
        //非HOME组的，则在加载主题对应组文件夹的主题文件
        if (GROUP != 'Home') {
            $groupPath = GROUP . '/';
        } else {
            $groupPath = '';
        }
        if (empty($theme)) {
            $themeFile = THEME . '/Home/' . $this->theme['value'] . '/' . $groupPath . MODULE . '_' . ACTION . '.php';
            $this->checkThemeFileExist($themeFile, MODULE . '_' . ACTION . '.php');
            include $themeFile;
        } else {
            $themeFile = THEME . '/Home/' . $this->theme['value'] . '/' . $groupPath . $theme . '.php';
            $this->checkThemeFileExist($themeFile, "{$theme}.php");
            include $themeFile;
        }
    }

    /**
     * 验证验证码
     * @param type $formName 验证表单名称
     */
    protected function checkVerify($formName) {
        $verify = md5(strtolower($this->is_p($formName, '请填写验证码')));
        if ($verify != $_SESSION['verify']) {
            $this->error('验证码不正确!');
        }
        unset($_SESSION['verify']);
    }

}